package com.doubao.doubao.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.doubao.doubao.common.api.ApiResult;
import com.doubao.doubao.common.api.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FilesController {
    @Value("${server.port}")
    private String port;
    private static String ip ="http://localhost";


    @PostMapping("/upload")
    public ApiResult<?> upload(MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();  //获取源文件的名称
        String flag= IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/Spring-hou/src/main/resources/files/" + flag+"_" +originalFilename; //获取上传路径
        FileUtil.writeBytes(file.getBytes(),rootFilePath);   //把文件写入到上传的路径
        return ApiResult.success(ip+":"+port+"/files/"+flag);   //结果返回url
    }

    //    富文本图片上传接口
    @PostMapping("/editor/upload")
    public JSON editorupload(MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();  //获取源文件的名称
//        定义文件的唯一标识
        String flag= IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir")+ "/Spring-hou/src/main/resources/files/" + flag + " _ "+originalFilename; //获取上传路径
        FileUtil.writeBytes(file.getBytes(),rootFilePath);   //把文件写入到上传的路径
        String url =ip+":"+port+"/files/"+flag;
        JSONObject json=new JSONObject();
        json.set("errno",0);
        JSONArray arr = new JSONArray();
        JSONObject data = new JSONObject();
        arr.add(data);
        data.set("url",url);
        json.set("data",arr);
        return json;  //结果返回url
    }


    //    下载接口
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;
        String basePath=System.getProperty("user.dir")+ "/Spring-hou/src/main/resources/files/" ;
        List<String> fileNames =FileUtil.listFileNames(basePath); //获取所有文件的名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); //找到参数一致的文件
        try {
            if(StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName); //通过文件的路径读取文件字节流
                os=response.getOutputStream(); //通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
        }

    }
}
